<?php
/**
 * Created by : PhpStorm
 * User: ZPF
 * Date: 2022/5/12
 * Time: 22:26
 */

namespace app\admin\model;

use think\Model;
use think\model\relation\HasMany;

class BomModel extends BaseModel
{
    protected $name = 'bom';
    protected $jsonAssoc=true;
    protected $json=['attribute_name','attribute_spec'];

    public function creator()
    {
        return $this->belongsTo(AdminModel::class, 'creator_id');
    }
    public function parentSku(){
        return $this->belongsTo(ClassifyModel::class,'parent_sku_id');
    }

    public static function onBeforeInsert($model)
    {
        $today = date('Y-m-d');
        $tomorrow = date('Y-m-d') . ' 23:59:59';
        $last = self::where('create_time', 'between', [$today, $tomorrow])->order('id desc')->find();
        $today = date('Ymd');
        if ($last) {
            $model->current_index = $last->current_index + 1;
            $model->no = $today . sprintf("%02d", $model->current_index);;
        } else {
            $model->no = $today . '01';
            $model->current_index = 1;
        }
    }
    public static function onAfterInsert($model)
    {
       if($model->level==0){
           $model->top_id = $model->id;
       }else{
           $parent = self::where('id','=',$model->parent_id)->find();
           $model->top_id = $parent->top_id;
       }
       $model->save();
    }

    public function children()
    {
        return $this->hasMany(self::class, 'parent_id', 'id');
    }
    public function sku(){
        return $this->belongsTo(ClassifyModel::class,'sku_id','id');
    }
    public static function onBeforeDelete(Model $model)
    {
        $list = self::where('parent_id','=',$model->id)->select();
        foreach ($list as $item){
            $item->delete();
        }
    }

}
